# -*- coding: utf-8 -*-
from flask import Flask, jsonify, render_template, request
from flask_cors import CORS
import time
import threading
import json
# from flask_sslify import SSLify
import ssl
from com_data import weather_mgr
from com_serial import loopFunGetData
from com_socket import socket_start_server, socket_send_data
from com_process import process_socket_get

app = Flask(__name__)
CORS(app)  # 解决跨域问题
context = (r'ssl/guaguagua.icu_bundle.pem', r'ssl/guaguagua.icu.key')

######################## 气象站 #####################################################################

@app.route('/api/timestamp')
def get_timestamp():
    # 返回当前时间戳（Unix时间）
    current = weather_mgr.get_current_data()
    # print(f"当前温度：{current['temperature']}℃")
    print("temperature:", current)
    return jsonify({"timestamp": int(time.time())})

# 仅渲染静态HTML页面
@app.route('/')
def home():
    return render_template('index.html')  # 直接返回HTML文件

@app.route('/qixiang')
def qixiang():
    return render_template('qixiang.html')  # 直接返回HTML文件

@app.route('/api/weather')
def get_qixiang():
    current = weather_mgr.get_current_data()
    print("temperature:", current)
    return jsonify({"temperature": current['temperature'], "humidity": 12, "pressure": 12, "wind-speed": 121, "wind-direction": 1})
    # 温度范围：15-35℃


##################### 博物馆 ########################################################################

# 仅渲染静态HTML页面
@app.route('/bowuguan')
def bowuguan():
    return render_template('bowuguan.html')  # 直接返回HTML文件

@app.route('/bowuguan/api')
def get_data():
    bowuguan_data = process_socket_get("bowuguan")
    return jsonify({
         "data": {
             "temperature": bowuguan_data['temperature'],
             "humidity":bowuguan_data['humidity'],
             "light": bowuguan_data['light'],
             "people": bowuguan_data['people']
         }
    })

@app.route('/bowuguan/api/submit', methods=['POST'])
def set_mode():

    print("设置工作模式")
    data = request.get_json()

    print(data)
    if not data or 'mode' not in data:
        return jsonify({"status": "error", "message": "无效请求"}), 400

    new_mode = data['mode']

    if new_mode not in ["监护模式", "浏览模式"]:
        return jsonify({"status": "error", "message": "无效的工作模式"}), 400
    else :
        if (new_mode == "监护模式") :
            print("下发监护模式")
            bowuguan_data = process_socket_get("bowuguan")
            if bowuguan_data["socket"] != 0:
                rev = socket_send_data(bowuguan_data["socket"], "{\"set\":\"wr\"}\r\n")
                if rev is False:
                    new_mode = "设备无法连接不在线"
            else:
                new_mode = "设备不在线"
        if (new_mode == "浏览模式") :
            print("下发浏览模式")
            bowuguan_data = process_socket_get("bowuguan")
            if bowuguan_data["socket"] != 0:
                rev = socket_send_data(bowuguan_data["socket"], "{\"set\":\"vs\"}\r\n")
                if rev is False:
                    new_mode = "设备无法连接不在线"
            else:
                new_mode = "设备不在线"

    return jsonify({
        "status": "success",
        "current_mode": new_mode
    })

#############################################################################################


##################### 智能家居 ########################################################################
@app.route('/smartHome/api/getmessage')
def get_home_data():
    bowuguan_data = process_socket_get("home")
    return jsonify({
         "data": {
             "temperature": bowuguan_data['temperature'],
             "humidity":bowuguan_data['humidity'],
             "light": bowuguan_data['light'],
             "people": bowuguan_data['people'],
             "co2": bowuguan_data['co2'],
             "smock": bowuguan_data['smock'],
             "soil": bowuguan_data['soil'],
         }
    })

@app.route('/smartHome/api/setmessage', methods=['POST'])
def set_home_mode():
    print("设置工作模式")
    data = request.get_json()
    print(data)

    if "motor" in data:
        # sendStr = "{:d}:{:d}:{:02d}\r\n".format(1, data["key"], data["motor"])
        data = {
            'type':1,
            'key':data["key"],
            'val':data["motor"]
        }
        sendStr = json.dumps(data)
        print("---------", sendStr)
    elif "light" in data:
        # sendStr = "{:d}:{:d}:{:02d}\r\n".format(2, data["key"], data["light"])
        data = {
            'type':2,
            'key':data["key"],
            'val':data["light"]
        }
        sendStr = json.dumps(data)
        print("---------", sendStr)
    elif "soil" in data:
        # sendStr = "{:d}:{:d}:{:02d}\r\n".format(2, data["key"], data["light"])
        data = {
            'type':3,
            'key':data["key"],
            'val':data["soil"]
        }
        sendStr = json.dumps(data)
        print("---------", sendStr)
    else:
        print ("错误数据")
        return jsonify({
            "status": "error",
            "current_mode": "错误数据"
        })


    print("sand data ", sendStr)
    homeData = process_socket_get("home")
    if homeData["socket"] != 0:
        rev = socket_send_data(homeData["socket"], sendStr)
        if rev is False:
            new_mode = "设备无法连接不在线"
            print("socket 发送给设备失败")
        else:
            new_mode = "设置成功"
            print("socket 发送给设备成功")
    else:
        new_mode = "设备不在线"
        print("socket 设备不在线")

    return jsonify({
        "status": "success",
        "current_mode": new_mode
    })

#############################################################################################


def run_flask_app():
    app.run(host='0.0.0.0', port=443, ssl_context=context) # https
    # app.run(host='0.0.0.0', port=80) # http

if __name__ == '__main__':

    # 启动Socket线程
    socket_thread = threading.Thread(target=socket_start_server)
    socket_thread.daemon = True  # 设为守护线程，随主线程退出
    socket_thread.start()

    socket_thread = threading.Thread(target=run_flask_app)
    socket_thread.daemon = True  # 设为守护线程，随主线程退出
    socket_thread.start()

    while(1):
        pass